import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Main {
    static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    static final Scanner sc = new Scanner(System.in);

    static UserStore userStore = new UserStore();
    static Map<String, Theater> theaters = new LinkedHashMap<>();
    static Map<String, Movie> movies = new LinkedHashMap<>();
    static Map<String, ShowSession> sessions = new LinkedHashMap<>();

    // 当前登录用户
    static User currentUser = null;

    // 统一的初始数据
    static void initData() {
        // Admin admin
        Admin admin = new Admin("ADM001", "admin", "010-0000-0000", "ynuinfo#777", LocalDateTime.now());
        userStore.addUser(admin);

        // 经理/前台示例
        Manager m1 = new Manager("MGR001", "manager1", "010-1111-1111", "123456", LocalDateTime.now());
        FrontDesk f1 = new FrontDesk("FD001", "front1", "010-2222-2222", "123456", LocalDateTime.now());
        userStore.addUser(m1);
        userStore.addUser(f1);

        // 库存厅
        theaters.put("黄金厅", new Theater("黄金厅", 8, 10));
        theaters.put("白银厅", new Theater("白银厅", 10, 12));
        theaters.put("翡翠厅", new Theater("翡翠厅", 7, 8));
        theaters.put("钻石厅", new Theater("钻石厅", 7, 8));
        theaters.put("宝石厅", new Theater("宝石厅", 8, 9));

        // 影片
        Movie mv1 = new Movie("流浪地球", "郭帆", "吴京、章子怡", "科幻片", 130, 8.5);
        Movie mv2 = new Movie("阿凡达：水之道", "詹姆斯·卡梅隆", "詹姆斯·卡梅隆", "科幻片", 162, 7.9);
        movies.put(mv1.title, mv1);
        movies.put(mv2.title, mv2);

        // 场次
        ShowSession s1 = new ShowSession("S001", mv1, "黄金厅", "2025-08-28 19:00", 68.0);
        ShowSession s2 = new ShowSession("S002", mv2, "白银厅", "2025-08-28 20:30", 60.0);
        sessions.put(s1.sessionId, s1);
        sessions.put(s2.sessionId, s2);
    }

    // ----------------- 主逻辑 -----------------

    public static void main(String[] args) {
        initData();
        while (true) {
            showMainMenu();
        }
    }

    static void showMainMenu() {
        System.out.println("\n==== 影城管理系统 ====");
        System.out.println("1. 登录");
        System.out.println("2. 退出");
        System.out.print("请选择：");
        String choice = sc.nextLine().trim();
        switch (choice) {
            case "1":
                loginFlow();
                break;
            case "2":
                System.out.println("再见！");
                System.exit(0);
                break;
            default:
                System.out.println("无效输入，请重新选择。");
        }
    }

    static void loginFlow() {
        System.out.print("用户名：");
        String name = sc.nextLine().trim();
        System.out.print("密码：");
        String pass = sc.nextLine().trim();

        User user = null;
        // 简单按用户名查找
        for (User u : userStore.listAll()) {
            if (u.getUserName().equals(name) && u.getPassword().equals(pass)) {
                user = u;
                break;
            }
        }

        if (user == null) {
            System.out.println("登录失败，用户名或密码错误。");
            return;
        }

        currentUser = user;
        System.out.println("欢迎，" + currentUser.getUserName() + "  (" + currentUser.getRole() + ")");
        if ("ADMIN".equals(currentUser.getRole())) adminMenu();
        else if ("MANAGER".equals(currentUser.getRole())) managerMenu();
        else if ("FRONT".equals(currentUser.getRole())) frontMenu();
        else {
            System.out.println("未知角色。");
            currentUser = null;
        }
    }

    // ----------------- 管理员菜单与操作 -----------------

    static void adminMenu() {
        while (true) {
            System.out.println("\n[管理员菜单]");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置非管理员用户密码");
            System.out.println("3. 用户管理");
            System.out.println("4. 日志查看（简化）");
            System.out.println("5. 退出登录");
            System.out.print("请选择：");
            String c = sc.nextLine().trim();
            switch (c) {
                case "1":
                    adminChangeOwnPassword();
                    break;
                case "2":
                    adminResetUserPassword();
                    break;
                case "3":
                    adminUserManagement();
                    break;
                case "4":
                    System.out.println("日志查看请查看 log.txt 文件。");
                    break;
                case "5":
                    currentUser = null;
                    return;
                default:
                    System.out.println("无效输入。");
            }
        }
    }

    static void adminChangeOwnPassword() {
        System.out.print("输入新密码：");
        String newPwd = sc.nextLine().trim();
        currentUser.setPassword(newPwd);
        Logger.log(currentUser.getUserName(), "修改管理员密码");
        System.out.println("密码修改成功。下次登录请使用新密码。");
    }

    static void adminResetUserPassword() {
        System.out.print("请输入要重置密码的用户名：");
        String uname = sc.nextLine().trim();
        User u = userStore.getByName(uname);
        if (u == null) {
            System.out.println("用户不存在。");
            return;
        }
        if ("ADMIN".equals(u.getRole())) {
            System.out.println("不能重置管理员密码。");
            return;
        }
        String oldPwd = u.getPassword();
        u.setPassword("123456");
        Logger.log(currentUser.getUserName(), "重置前台/经理 " + uname + " 的密码，旧密码：" + oldPwd);
        System.out.println("密码已重置为 123456，登录时请尽快修改。");
    }

    static void adminUserManagement() {
        while (true) {
            System.out.println("\n[管理员 - 用户管理]");
            System.out.println("1. 列出所有用户");
            System.out.println("2. 查询用户");
            System.out.println("3. 增加用户");
            System.out.println("4. 修改用户信息");
            System.out.println("5. 删除用户");
            System.out.println("6. 返回上一级");
            System.out.print("请选择：");
            String opt = sc.nextLine().trim();
            switch (opt) {
                case "1":
                    listAllUsers();
                    break;
                case "2":
                    queryUser();
                    break;
                case "3":
                    addUserAdmin();
                    break;
                case "4":
                    modifyUserAdmin();
                    break;
                case "5":
                    deleteUserAdmin();
                    break;
                case "6":
                    return;
                default:
                    System.out.println("无效输入。");
            }
        }
    }

    static void listAllUsers() {
        System.out.println("----- 所有用户 -----");
        for (User u : userStore.listAll()) {
            System.out.println(u);
        }
    }

    static void queryUser() {
        System.out.print("按 ID 查询输入 1，按用户名查询输入 2：");
        String mode = sc.nextLine().trim();
        if ("1".equals(mode)) {
            System.out.print("输入用户ID：");
            String id = sc.nextLine().trim();
            User u = userStore.getById(id);
            if (u != null) System.out.println(u);
            else System.out.println("未找到用户。");
        } else if ("2".equals(mode)) {
            System.out.print("输入用户名：");
            String name = sc.nextLine().trim();
            User u = userStore.getByName(name);
            if (u != null) System.out.println(u);
            else System.out.println("未找到用户。");
        } else {
            System.out.println("无效输入。");
        }
    }

    static void addUserAdmin() {
        System.out.print("输入新用户名：");
        String uname = sc.nextLine().trim();
        if (userStore.getByName(uname) != null) {
            System.out.println("用户名已存在。");
            return;
        }
        System.out.print("输入用户手机号：");
        String phone = sc.nextLine().trim();
        System.out.print("输入角色 (MANAGER/FRONT) ：");
        String role = sc.nextLine().trim().toUpperCase();
        if (!"MANAGER".equals(role) && !"FRONT".equals(role)) {
            System.out.println("无效角色。");
            return;
        }
        String newId = generateId(role);
        LocalDateTime now = LocalDateTime.now();
        User newUser;
        if ("MANAGER".equals(role)) newUser = new Manager(newId, uname, phone, "123456", now);
        else newUser = new FrontDesk(newId, uname, phone, "123456", now);
        userStore.addUser(newUser);
        Logger.log(currentUser.getUserName(), "增加 " + role + " 用户 " + uname);
        System.out.println("用户已创建，默认密码 123456，首次登录需修改。ID: " + newId);
    }

    static void modifyUserAdmin() {
        System.out.print("输入要修改的用户名：");
        String uname = sc.nextLine().trim();
        User u = userStore.getByName(uname);
        if (u == null) {
            System.out.println("用户不存在。");
            return;
        }
        System.out.print("修改为新手机号：");
        String newPhone = sc.nextLine().trim();
        System.out.print("修改角色（MANAGER/FRONT），若不改回车跳过：");
        String newRole = sc.nextLine().trim().toUpperCase();
        if (!newRole.isEmpty()) {
            if (!"MANAGER".equals(newRole) && !"FRONT".equals(newRole)) {
                System.out.println("无效角色，跳过。");
            } else {
                u.setRole(newRole);
            }
        }
        if (!newPhone.isEmpty()) u.setPhone(newPhone);
        Logger.log(currentUser.getUserName(), "修改用户信息 " + uname);
        System.out.println("用户信息已更新。");
    }

    static void deleteUserAdmin() {
        System.out.print("输入要删除的用户名：");
        String uname = sc.nextLine().trim();
        User u = userStore.getByName(uname);
        if (u == null) {
            System.out.println("用户不存在。");
            return;
        }
        if ("admin".equals(u.getUserName()) || "ADMIN".equals(u.getRole())) {
            System.out.println("不能删除 admin 用户。");
            return;
        }
        System.out.print("警告：删除将不可恢复，确认删除请输入 YES：");
        String confirm = sc.nextLine().trim();
        if ("YES".equalsIgnoreCase(confirm)) {
            userStore.removeUser(u);
            Logger.log(currentUser.getUserName(), "删除用户 " + uname);
            System.out.println("用户已删除。");
        } else {
            System.out.println("取消删除。");
        }
    }

    static String generateId(String role) {
        String prefix = "UNKNOWN";
        if ("MANAGER".equals(role)) prefix = "MGR";
        else if ("FRONT".equals(role)) prefix = "FD";
        String tail = String.valueOf(new Random().nextInt(900) + 100);
        return prefix + tail;
    }

    // ----------------- 管理者/前台 其他简单菜单 -----------------

    static void managerMenu() {
        while (true) {
            System.out.println("\n[经理菜单]");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置前台用户密码");
            System.out.println("3. 影片管理（简化演示）");
            System.out.println("4. 退出登录");
            System.out.print("请选择：");
            String opt = sc.nextLine().trim();
            if ("1".equals(opt)) {
                System.out.print("输入新密码：");
                currentUser.setPassword(sc.nextLine().trim());
                Logger.log(currentUser.getUserName(), "修改经理密码");
                System.out.println("密码已修改。");
            } else if ("2".equals(opt)) {
                System.out.print("输入前台用户名：");
                String uname = sc.nextLine().trim();
                User u = userStore.getByName(uname);
                if (u != null && "FRONT".equals(u.getRole())) {
                    u.setPassword("123456");
                    Logger.log(currentUser.getUserName(), "重置前台密码 " + uname);
                    System.out.println("密码已重置为 123456。");
                } else {
                    System.out.println("未找到前台用户，或用户名非前台。");
                }
            } else if ("3".equals(opt)) {
                showManagerMovieDemo();
            } else if ("4".equals(opt)) {
                currentUser = null;
                return;
            } else {
                System.out.println("无效输入。");
            }
        }
    }

    static void showManagerMovieDemo() {
        // 简化：列出影片、添加、删除的演示入口
        while (true) {
            System.out.println("\n[影片管理演示]");
            System.out.println("1. 列出影片");
            System.out.println("2. 添加影片");
            System.out.println("3. 修改影片");
            System.out.println("4. 删除影片");
            System.out.println("5. 返回上一级");
            System.out.print("请选择：");
            String opt = sc.nextLine().trim();
            if ("1".equals(opt)) {
                if (movies.isEmpty()) System.out.println("无影片信息。");
                else {
                    for (Movie m : movies.values()) System.out.println(m);
                }
            } else if ("2".equals(opt)) {
                System.out.print("片名：");
                String t = sc.nextLine().trim();
                System.out.print("导演：");
                String d = sc.nextLine().trim();
                System.out.print("主演：");
                String s = sc.nextLine().trim();
                System.out.print("时长（分）：");
                int dur = readInt();
                System.out.print("评分（0-10）：");
                double rate = readDouble();
                Movie m = new Movie(t, d, s, "", dur, rate);
                movies.put(t, m);
                Logger.log(currentUser.getUserName(), "添加影片 " + t);
                System.out.println("影片已添加。");
            } else if ("3".equals(opt)) {
                System.out.print("输入要修改的影片名：");
                String name = sc.nextLine().trim();
                Movie m = movies.get(name);
                if (m == null) {
                    System.out.println("未找到影片。");
                } else {
                    System.out.print("新片名（如不改留空）：");
                    String newName = sc.nextLine().trim();
                    if (!newName.isEmpty()) m.title = newName;
                    System.out.print("新导演：");
                    String nd = sc.nextLine().trim();
                    if (!nd.isEmpty()) m.director = nd;
                    System.out.print("新主演：");
                    String ns = sc.nextLine().trim();
                    if (!ns.isEmpty()) m.stars = ns;
                    System.out.print("新时长（分）：");
                    String sd = sc.nextLine().trim();
                    if (!sd.isEmpty()) m.duration = Integer.parseInt(sd);
                    System.out.print("新评分：");
                    String sr = sc.nextLine().trim();
                    if (!sr.isEmpty()) m.rating = Double.parseDouble(sr);
                    Logger.log(currentUser.getUserName(), "修改影片 " + name);
                    System.out.println("影片已更新。");
                }
            } else if ("4".equals(opt)) {
                System.out.print("输入要删除的影片名：");
                String delName = sc.nextLine().trim();
                if (movies.containsKey(delName)) {
                    System.out.print("警告：删除后不可恢复，确认删除？(YES/NO): ");
                    String con = sc.nextLine().trim();
                    if ("YES".equalsIgnoreCase(con)) {
                        movies.remove(delName);
                        Logger.log(currentUser.getUserName(), "删除影片 " + delName);
                        System.out.println("影片已删除。");
                    }
                } else {
                    System.out.println("未找到影片。");
                }
            } else if ("5".equals(opt)) {
                return;
            } else {
                System.out.println("无效输入。");
            }
        }
    }

    static void frontMenu() {
        while (true) {
            System.out.println("\n[前台菜单]");
            System.out.println("1. 登录退出（本示例直接返回）");
            System.out.println("2. 列出正在上映影片");
            System.out.println("3. 列出所有场次（简化最近一周）");
            System.out.println("4. 退出登录");
            System.out.print("请选择：");
            String opt = sc.nextLine().trim();
            if ("1".equals(opt) || "4".equals(opt)) {
                currentUser = null;
                return;
            } else if ("2".equals(opt)) {
                listMovies();
            } else if ("3".equals(opt)) {
                listSessions();
            } else {
                System.out.println("无效输入。");
            }
        }
    }

    static void listMovies() {
        System.out.println("正在上映影片：");
        for (Movie m : movies.values()) System.out.println(m);
    }

    static void listSessions() {
        System.out.println("最近场次（简化展示）:");
        for (ShowSession ss : sessions.values()) {
            System.out.println("场次ID:" + ss.sessionId + "  影片:" + ss.movie.title +
                    "  放映厅:" + ss.theaterName + "  时间:" + ss.time + "  票价:" + ss.price);
        }
    }

    // ----------------- 实用工具 -----------------

    static int readInt() {
        while (true) {
            String s = sc.nextLine().trim();
            try {
                return Integer.parseInt(s);
            } catch (NumberFormatException e) {
                System.out.print("请输入一个整数：");
            }
        }
    }

    static double readDouble() {
        while (true) {
            String s = sc.nextLine().trim();
            try {
                return Double.parseDouble(s);
            } catch (NumberFormatException e) {
                System.out.print("请输入一个数字（如 8.5）：");
            }
        }
    }
}
